<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Task;

use App\Model\Play;
use App\Utils\Enum;

class SyncAbnormalMatchTask extends AbstractBaseTask
{
    const ABNORMAL_TIME = 15 * 86400;
    public function execute(): void
    {
        $curId = 0;
        while (true) {
            $matchList = Play::query()->where([['id', '>', $curId], ['match_status', '=', Enum\MatchEnum::MATCH_STATUS_WAIT], ['match_time', '<', time() - 600]])->orderBy('id')->limit(100)->select()->get();
            if ($matchList->isEmpty()) {
                break;
            }
            foreach ($matchList as $match) {
                $curId = $match['id'];
                $data = $this->api->getMatchInfo($match['match_id']);
                if ($data && !empty($data['data']['result'])) {
                    $detail = &$data['data']['result']['match'];
                    $update = [
                        'match_status' => $detail['matchStatus'] == Enum\MatchEnum::MATCH_STATUS_WAIT && time() - $detail['matchTime'] > self::ABNORMAL_TIME ? Enum\MatchEnum::MATCH_STATUS_ABNORMAL : $detail['matchStatus'],
                        'match_status_id' => $data['data']['result']['match']['statusId'],
                        'video_url' => $data['data']['result']['match']['videoUrl'] ?? '',
                        'animate_url' => isset($data['data']['result']['animation']) && !empty($data['data']['result']['animation']['url']) ? $data['data']['result']['animation']['url'] : '',
                    ];
                    if ($match['match_time'] != $data['data']['result']['match']['matchTime']) {
                        $update['match_time'] = $data['data']['result']['match']['matchTime'];
                    }
                    if (isset($data['data']['result']['match']['vbScores'])) {
                        $update['vb_scores'] = new_json_encode($data['data']['result']['match']['vbScores']);
                    } else {
                        $update['home_team_scores'] = new_json_encode($data['data']['result']['match']['homeScores']);
                        $update['away_team_scores'] = new_json_encode($data['data']['result']['match']['awayScores']);
                    }
                    Play::query()->where('id', $match['id'])->update($update);
                    $this->logger->warning(sprintf('成功更新异常比赛(%s) %s %s VS %s', $match['match_id'], date('Y-m-d H:i', $match['match_time']), $match['home_team_name'], $match['away_team_name']));
                }
            }
        }

    }
}